#!/bin/bash
set -e

echo -e "\e[32m  腾讯  阿里云 UBUNTU debian完美运行...\e[0m"
echo -e "\e[32m[1/6] 配置Docker国内镜像加速...\e[0m"
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://docker.1panel.live"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  }
}
EOF

echo -e "\e[32m[2/6] 安装Docker和Docker Compose...\e[0m"
sudo apt update
sudo apt install -y docker.io docker-compose
if ! command -v docker &> /dev/null; then
    echo -e "\e[31m❌ Docker安装失败，请检查网络连接\e[0m"
    exit 1
fi
sudo systemctl restart docker
sudo systemctl enable docker

echo -e "\e[36m请输入要安装的青龙版本（推荐 2.16.3，直接回车使用默认值）：\e[0m"
read -r QL_VERSION
QL_VERSION=${QL_VERSION:-2.16.3}

echo -e "\e[32m[3/6] 创建青龙面板目录...\e[0m"
mkdir -p "$HOME/qinglong"
cd "$HOME/qinglong" || exit

echo -e "\e[32m[4/6] 创建docker-compose.yml文件...\e[0m"
cat > docker-compose.yml <<EOF
version: '3.7'
services:
  qinglong:
    image: whyour/qinglong:$QL_VERSION
    container_name: qinglong
    restart: unless-stopped
    ports:
      - "5700:5700"
    volumes:
      - ./ql/config:/ql/config
      - ./ql/log:/ql/log
      - ./ql/db:/ql/db
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
EOF

echo -e "\e[32m[5/6] 启动青龙面板（首次启动可能需要2-5分钟）...\e[0m"
if ! sudo docker-compose up -d; then
    echo -e "\e[33m⚠️ 主镜像源拉取失败，尝试备用镜像源...\e[0m"
    sed -i 's|whyour/qinglong|registry.cn-hangzhou.aliyuncs.com/qinglong/qinglong|' docker-compose.yml
    sudo docker-compose up -d || {
        echo -e "\e[31m❌ 所有镜像源均失败，请检查网络或手动下载镜像\e[0m"
        exit 1
    }
fi

echo -e "\e[32m[6/6] 验证安装...\e[0m"
for i in {1..20}; do
    if sudo docker ps | grep -q qinglong; then
        SERVER_IP=$(curl -s ifconfig.me || hostname -I | awk '{print $1}')
        echo -e "\e[32m✅ 青龙面板(v$QL_VERSION)已成功启动\e[0m"
        echo -e "\n\e[1;36m访问地址: http://${SERVER_IP}:5700\e[0m"
        echo -e "\e[33m首次启动可能需要等待1-2分钟才能访问页面\e[0m"
        break
    fi
    sleep 5
    [ $i -eq 10 ] && echo -e "\e[33m⚠️ 启动时间较长，请耐心等待...\e[0m"
done

if ! sudo docker ps | grep -q qinglong; then
    echo -e "\e[31m❌ 启动失败，请检查日志: sudo docker logs qinglong\e[0m"
    exit 1
fi

echo -e "\n\e[1;34m管理命令:\e[0m"
echo -e "\e[33m重启青龙: docker restart qinglong\e[0m"
echo -e "\e[33m查看状态: docker ps\e[0m"
echo -e "\e[33m查看日志: docker logs -f qinglong\e[0m"
echo -e "\e[33m备份数据: tar -czvf ql_backup.tar.gz ~/qinglong/ql\e[0m"
echo -e "\e[33m升级版本: 修改nano docker-compose.yml中的版本号后执行 docker-compose up -d --force-recreate\e[0m"
echo -e "\e[1;31m⚠️ 重要提示：首次访问后请立即修改默认密码！\e[0m"